package cn.eva.service.Impl.admin;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.eva.common.LayuiTableResult;
import cn.eva.common.ResultJosn;
import cn.eva.dao.EvaManagerMapper;
import cn.eva.dao.SysUserRoleMapper;
import cn.eva.dto.SysManagerAdd;
import cn.eva.dto.SysUserSelect;
import cn.eva.entity.EvaManager;
import cn.eva.entity.SysUserRoleKey;
import cn.eva.example.EvaManagerExample;
import cn.eva.example.EvaManagerExample.Criteria;
import cn.eva.example.SysUserRoleExample;
import cn.eva.service.admin.SysManagerService;
import cn.eva.service.admin.UserRoleService;
import cn.eva.utils.UUIDUtils;

@Service
public class SysManagerServiceImpl implements SysManagerService {

    @Autowired
    private EvaManagerMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 添加用户
     */
    @Override
    @Transactional
    public ResultJosn add(SysManagerAdd user) {
        EvaManager check = this.checkusername(user.getmAccount());
        if (null != check) {
            throw new IllegalArgumentException("用户名已存在");
        }
        user.setmId(UUIDUtils.getUUID());
        EvaManager u1 = (EvaManager) user;
        u1.setmPass(passwordEncoder.encode(u1.getmPass()));
        u1.setCreateTime(new Date());
        u1.setUpdateTime(new Date());
        userMapper.insertSelective(u1);
        // 保存user权限
        saveUserRoles(u1.getmId(), user.getRoleIds());
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), user);
    }

    /**
     * 单个、批量删除（在数据框中真正的删除了）
     */
    @Override
    @Transactional
    public ResultJosn delete(List<String> uids) {
        if (CollectionUtils.isEmpty(uids)) {
            throw new IllegalArgumentException("参数错误");
        }
        EvaManagerExample example = new EvaManagerExample();
        example.createCriteria().andMIdIn(uids);
        userRoleService.delByUids(uids);
        userMapper.deleteByExample(example);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "操作成功");
    }

    /**
     * 更新信息 根据uid
     */
    @Override
    @Transactional
    public ResultJosn updateByExample(SysManagerAdd user) {
        ResultJosn resultJosn = null;
        if (StringUtils.isBlank(user.getmId())) {
            throw new IllegalArgumentException("uid错误");
        }
        EvaManager check = this.checkusername(user.getmAccount());
        if (null != check && !(check.getmId()).equals(user.getmId())) {
            throw new IllegalArgumentException("账号已存在");
        }
        user.setUpdateTime(new Date());
        EvaManager u1 = (EvaManager) user;
        userMapper.updateByPrimaryKeySelective(u1);
        // 保存user权限
        saveUserRoles(u1.getmId(), user.getRoleIds());
        resultJosn = new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "操作成功");
        return resultJosn;
    }

    /**
     * 用户模糊查询
     */
    @Override
    @Transactional
    public LayuiTableResult selectByExample(EvaManager user, Integer page, Integer pageSize) {
        LayuiTableResult resultJosn = new LayuiTableResult();
        // 构造条件
        EvaManagerExample example = new EvaManagerExample();
        example.setOrderByClause("create_time DESC");
        Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(user.getmAccount())) {
            // m_accout（账号）精确查找
            criteria.andMAccountLike("%" + user.getmAccount() + "%");
        }
        // 开启分页查找
        PageHelper.startPage(page, pageSize);
        List<EvaManager> list = userMapper.selectByExample(example);
        PageInfo<EvaManager> pageInfo = new PageInfo<>(list, pageSize);
        //
        resultJosn.setCode(HttpStatus.OK.value());
        resultJosn.setMessage(HttpStatus.OK.getReasonPhrase());
        resultJosn.setCount(pageInfo.getTotal());
        resultJosn.setData(pageInfo.getList());
        return resultJosn;
    }

    /**
     * 根据uid查找用户信息、包括角色
     */
    @Override
    public ResultJosn selectByUid(String uid) {
        /*
         * 在阿里巴巴开发规范中，单操作两张表的时候应该建立索引； 这里是做链接查询，后期再看
         */
        if (StringUtils.isBlank(uid)) {
            throw new IllegalArgumentException("uid错误");
        }
        SysUserSelect result = userMapper.selectByUid(uid);
        return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), result);
    }

    /**
     * 根据accout判断是否注册过，返回根据accout查询出来的对象
     * 
     * @param accout
     * @return
     */
    public EvaManager checkusername(String accout) {
        EvaManagerExample example = new EvaManagerExample();
        example.createCriteria().andMAccountEqualTo(accout);
        List<EvaManager> list = userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return (EvaManager) list.get(0);
    }

    /**
     * 保存用户角色
     * 
     * @param uid
     * @param roleIds
     */
    private void saveUserRoles(String uid, List<Long> roleIds) {
        // 先删除user权限，再添加
        if (!CollectionUtils.isEmpty(roleIds)) {
            SysUserRoleExample example = new SysUserRoleExample();
            example.createCriteria().andUidEqualTo(uid);
            userRoleMapper.deleteByExample(example);
            for (Long r : roleIds) {
                SysUserRoleKey user_role = new SysUserRoleKey();
                user_role.setUid(uid);
                user_role.setRoleId(r);
                userRoleMapper.insert(user_role);
            }
        }
    }
}
